<template>
  <div class="pagination">
    <!-- 如果当前页 -->
    <button :disabled="pageNo === 1" @click="$emit('clickPage', pageNo - 1)">
      上一页
    </button>
    <!-- 等于1的时候不显示 -->
    <button
      v-show="pageStartEnd.start > 1"
      :class="{ active: pageNo === 1 }"
      @click="$emit('clickPage', 1)"
    >
      1
    </button>
    <button v-show="pageStartEnd.start > 2">···</button>

    <button
      v-for="page in pageArr"
      :key="page"
      :class="{ active: pageNo === page }"
      @click="$emit('clickPage', page)"
    >
      {{ page }}
    </button>

    <button v-show="pageStartEnd.end < totalPages - 1">···</button>
    <!-- 总页数 -->
    <button
      v-show="pageStartEnd.end < totalPages"
      @click="$emit('clickPage', totalPages)"
    >
      {{ totalPages }}
    </button>
    <button @click="$emit('clickPage', pageNo + 1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "PageNumber",
  // pageNo当前页数  totalPages:总页数  total:总条数 continueNum:连续页数
  props: ["pageNo", "total", "totalPages", "continueNum"],
  computed: {
    // 起始坐标和终止坐标
    pageStartEnd() {
      // 首先拿到传来的值
      let { pageNo, totalPages, continueNum } = this;
      // 设置起始点和终止点
      let start = 0;
      let end = 0;
      // 如果连续页数大于总页数 起始页码就是1 终止就是总页数
      if (continueNum > totalPages) {
        start = 1;
        end = totalPages;
      } else {
        // 设置起始和终止为当前页数+-2的上下范围
        start = pageNo - Math.floor(continueNum / 2);
        end = pageNo + Math.floor(continueNum / 2);
        //如果起始页小于1 起始页就是第一页 终结页就是连续页数
        if (start < 1) {
          start = 1;
          end = continueNum;
        }
        // 如果终止页大于总页数
        if (end > totalPages) {
          end = totalPages;
          start = totalPages - continueNum + 1;
        }
      }
      return { start, end };
    },
    // 对数字页码进行处理 产生一个数组 遍历结束的 如果大于起始的值就放进入
    pageArr() {
      const arr = [];
      for (let i = 1; i <= this.pageStartEnd.end; i++) {
        if (i >= this.pageStartEnd.start) {
          arr.push(i);
        }
      }
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>